package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 注册用户资源控制器
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private ITravelService travelService;

    /**
     * 用户注册资源
     * @param user 注册信息
     * @return 注册结果
     */
    @PostMapping
    public JSONResult register(User user) {
        JSONResult jsonResult = new JSONResult();
        try {
            userService.saveOrUpdate(user);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark(e.getMessage());
        }
        return jsonResult;
    }

    /**
     * 用户信息修改资源
     * @param user 前端传入的用户信息
     * @return 返回修改结果
     */
    @PutMapping("{id}")
    public JSONResult saveOrUpdate(User user) {
        JSONResult jsonResult = new JSONResult();
        userService.saveOrUpdate(user);
        //保存成功，将前端数据回传以设置到sessionStorage回显
        jsonResult.setResult(user);
        return jsonResult;
    }

    /**
     * 获取我的游记
     * @param queryObject
     * @return
     */
    @GetMapping("/{authorId}/travels")
    public PageInfo queryTravel(TravelQueryObject queryObject) {
        queryObject.setOrderBy("t.lastUpdateTime desc");
        PageInfo pageInfo= travelService.query(queryObject);
        return pageInfo;
    }
    @GetMapping("{id}")
    public JSONResult getUserById(@PathVariable Long id) {
        JSONResult jsonResult = new JSONResult();
        User user = userService.getUserById(id);
        jsonResult.setResult(user);
        return jsonResult;
    }
}
